import React from 'react';
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { IStudent } from '../../types';
import styles from './Charts.module.css';

interface ChartsProps {
  students: IStudent[];
}

const Charts: React.FC<ChartsProps> = ({ students }) => {
  // 计算男女学生比例数据
  const genderData = [
    { name: '男', value: students.filter(s => s.gender === '男').length },
    { name: '女', value: students.filter(s => s.gender === '女').length }
  ];

  // 计算各年级学生数量数据
  const gradeCounts: Record<string, number> = {};
  students.forEach(student => {
    const grade = student.grade || '未分配';
    gradeCounts[grade] = (gradeCounts[grade] || 0) + 1;
  });

  const gradeData = Object.keys(gradeCounts).map(grade => ({
    name: grade,
    count: gradeCounts[grade]
  }));

  // 饼图颜色
  const COLORS = ['#0088FE', '#00C49F'];

  return (
    <div className={styles.chartsContainer}>
      <div className={styles.chartCard}>
        <h3 className={styles.chartTitle}>男女学生比例</h3>
        <div className={styles.chartWrapper}>
          <ResponsiveContainer width="100%" height="100%">
            <PieChart>
              <Pie
                data={genderData}
                cx="50%"
                cy="50%"
                labelLine={true}
                outerRadius={80}
                fill="#8884d8"
                dataKey="value"
                label={({ name, percent }) => `${name}: ${((percent as number) * 100).toFixed(0)}%`}
              >
                {genderData.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                ))}
              </Pie>
              <Tooltip formatter={(value) => [value, '人数']} />
              <Legend />
            </PieChart>
          </ResponsiveContainer>
        </div>
      </div>

      <div className={styles.chartCard}>
        <h3 className={styles.chartTitle}>各年级学生数量</h3>
        <div className={styles.chartWrapper}>
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={gradeData}
              margin={{
                top: 5,
                right: 30,
                left: 20,
                bottom: 5,
              }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip formatter={(value) => [value, '人数']} />
              <Legend />
              <Bar dataKey="count" fill="#82ca9d" name="学生数量" />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </div>
    </div>
  );
};

export default Charts;